package common.config;

import com.p6spy.engine.common.P6Util;
import com.p6spy.engine.logging.Category;
import com.p6spy.engine.spy.appender.MultiLineFormat;

import org.hibernate.engine.jdbc.internal.FormatStyle;
import java.util.Locale;

/**
 * 用于自定义py6spy的输出格式
 *
 * @author 杨健
 * @since 2019/7/10 11:48
 */
public class P6spyFormatConfig extends MultiLineFormat {

    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
        sql = formatSql(category,sql);
        return now + " | took " + elapsed + "ms | category " + category + " | connectionId " + connectionId + " | sqlWithParameter: " + P6Util.singleLine(prepared) + sql;
    }

    private String formatSql(String category,String sql) {
        if(sql == null || sql.trim().equals("")) return sql;

        if(Category.STATEMENT.getName().equals(category)) {
            String tmpSql = sql.trim().toLowerCase(Locale.ROOT);
            if(tmpSql.startsWith("create") || tmpSql.startsWith("alter") || tmpSql.startsWith("comment")) {
                sql = FormatStyle.DDL.getFormatter().format(sql);
            }else {
                sql = FormatStyle.BASIC.getFormatter().format(sql);
            }
            sql = " | \nFormatSql(P6Spy sql,Hibernate format):" + sql;
        }

        return sql;
    }
}
